<?php

namespace app\data\command;

use app\data\service\AliService;
use Intervention\Image\ImageManager;
use think\admin\Command;
use think\admin\Exception;
use think\admin\Storage;
use think\console\Input;
use think\console\Output;
use think\facade\Log;

/**
 * 测试
 * Class WechatMessageOrcImage
 * @package app\data\command
 */
class WechatMessageOrcImage extends Command
{
    protected function configure()
    {
        $this->setName('wechat_message_orc_image');
        $this->setDescription('采集识别聊天记录图片');
    }

    /**
     * 业务指令执行
     * @param Input $input
     * @param Output $output
     * @return void
     * @throws Exception
     */
    protected function execute(Input $input, Output $output)
    {
        $destinationPath = '/data/wwwroot/work.szyoukejia.com/public/msgfile/wwde03d9b27ead4fad_bak/';

        while (true) {
            try {
                $folderPath = '/data/wwwroot/work.szyoukejia.com/public/msgfile/wwde03d9b27ead4fad';
                $files = scandir($folderPath);
                foreach ($files as $file) {
                    if (is_file($folderPath . '/' . $file)) {

                        $path = $folderPath . '/' . $file;
                        $fileSize = filesize($path);
                        if ($fileSize > 5 * 1024 * 1024) {

                            // 创建 ImageManager 实例
                            $imageManager = new ImageManager();

                            // 打开原始图片
                            $imageSize = getimagesize($path);
                            $image = $imageManager->make($path)->resize($imageSize[0] / 4, $imageSize[1] / 4);

                            // 设置压缩质量（可选）
                            $image->encode('png', 10);

                            // 保存压缩后的图片
                            $image->save($path);
                        }

                        $filename = pathinfo($path, PATHINFO_FILENAME);
                        $filename = explode('--', $filename);
                        $createTime = filectime($path);
                        if (($createTime + 30) < time()) {
                            $roomId = $filename[0];
                            $msgFrom = $filename[1];

                            $extension = pathinfo($path, PATHINFO_EXTENSION);
                            if (in_array($extension, ['jpg', 'jpeg', 'png'])) {
                                $uploadName = 'wechatMessage/' . pathinfo($path, PATHINFO_FILENAME) . '.' . pathinfo($path, PATHINFO_EXTENSION);

                                $bina = file_get_contents($path);
                                $info = Storage::instance('alioss')->set($uploadName, $bina, true, '');
                                $url = $info['url'] ?? '';
                                if (!empty($url)) {
                                    $types = ['face', 'back'];
                                    $message = [];
                                    foreach ($types as $type) {
                                        try {
                                            $message[$type] = AliService::instance()->recognizeDrivingLicense($url, $type);
                                        } catch (\Exception $e) {
                                            Log::error('采集图片-识别图片出错: ' . $e->getMessage());
                                            sleep(1);
                                        }
                                    }

                                    Log::info('采集图片-行驶证地址: ' . $url);
                                    Log::info('采集图片-行驶证数据: ' . json_encode($message));

                                    if (!empty($message['face']) && !empty($message['back'])) {
                                        if (!empty($message['face']['plate_number'])) {
                                            unset($message['back']['plate_number']);
                                        }
                                        $insertData = array_merge($message['face'], $message['back']);
                                        $insertData['uuid'] = 0;
                                        $insertData['source'] = 'YMM';
                                        $insertData['driving_image_1'] = $insertData['driving_image_2'] = $url;

                                        $record = $this->app->db->name('data_record')->where('plate_number', $insertData['plate_number'])->findOrEmpty();
                                        $insertData['province'] = $record['province'] ?? '';
                                        $insertData['city'] = $record['city'] ?? '';
                                        $insertData['area'] = $record['area'] ?? '';

                                        foreach ($insertData as $key => $datum) {
                                            if ($datum == '1970-01-01') {
                                                $insertData[$key] = null;
                                            }
                                        }
                                        if (!empty($insertData['plate_number'])) {
                                            $carInfo = $this->app->db->name('car_infos')->where('plate_number', $insertData['plate_number'])->findOrEmpty();
                                            if (!$carInfo) {
                                                $record = $this->app->db->name('data_record')->where('plate_number', $insertData['plate_number'])->findOrEmpty();
                                                if ($record) {
                                                    $insertData['phone'] = $record['phone'];
                                                }

                                                $this->app->db->name('car_infos')->insert($insertData);
                                            }
                                            unlink($path);
                                        } else {
                                            $this->saveFailLog($path, $msgFrom);
                                        }
                                    } else {
                                        $this->saveFailLog($path, $msgFrom);
                                    }
                                } else {
                                    $this->saveFailLog($path, $msgFrom);
                                }
                            } else {
                                unlink($path);
                            }
                        }
                    }
                }
            } catch (\Exception $exception) {

                $this->saveFailLog($path, $msgFrom);
                Log::error('采集图片-报错: ' . $exception->getMessage());
            }

            sleep(1);
        }
    }

    /**
     * 储存失败记录
     * @param $path
     * @return void
     */
    public function saveFailLog($path, $msgFrom)
    {
        $destinationPath = '/data/wwwroot/work.szyoukejia.com/public/msgfile/wwde03d9b27ead4fad_bak/';
        $basename = basename($path);
        rename($path, $destinationPath . $basename);
        $this->app->db->connect('car_review')->name('sync_fails')->insert(['name' => $basename, 'userid' => $msgFrom]);
    }




}